package net.lovesrc.allin.biz.pay;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.biz.jietu.JieTuService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PayService extends BaseService {

    @Autowired
    private JieTuService jieTuService;

    public File createWechatQrCode(String mobile) {
        return this.createQrCode("wechat", mobile);
    }

    public File createAlipayQrCode(String mobile) {
        return this.createQrCode("alipay", mobile);
    }

    private File createQrCode(String type, String mobile) {
        String filename = "pay-" + type + "-" + mobile;
        String url = UriComponentsBuilder.fromUriString("http://localhost:8080/jietu/pay/" + type)
                .queryParam("text", "https://qr.alipay.com/" + mobile)
                .toUriString();
        File file = jieTuService.newJieTu(url, filename);
        try {
            FileUtils.copyFileToDirectory(file, JieTuService.JIE_TU_DIR);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new File(JieTuService.JIE_TU_DIR, filename + ".png");
    }

    public List<PayAccount> getWorkeds() {
        List<JSONObject> rows = queryForRows(jdbcTemplate, "select * from t_pay_account where worked = 1 order by sort");
        return rows.stream()
                .map(r -> r.toJavaObject(PayAccount.class))
                .collect(Collectors.toList());
    }

    public List<PayAccount> getWorkedAlipays() {
        return getWorkeds()
                .stream()
                .filter(r -> StringUtils.isNotBlank(r.getAlipayFilename()))
                .collect(Collectors.toList());
    }

    public List<PayAccount> getWorkedWithBoth() {
        return getWorkeds()
                .stream()
                .filter(r -> StringUtils.isNotBlank(r.getAlipayFilename()) && StringUtils.isNotBlank(r.getWechatFilename()))
                .collect(Collectors.toList());
    }

}
